﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using PloobsEngine;

namespace Etapa1.SubdivisionSurface
{
    public class SimpleCurve
    {

        public DynamicVertexBuffer VertexBuffer;
        public VertexDeclaration VertexDeclaration;
        public int PrimitiveCount;
        public int VertexBufferSize;
        Vector3[] points;

        public SimpleCurve(Vector3[] points)
        {
            this.points = points;
            VertexDeclaration = new VertexDeclaration(EngineStuff.GraphicsDevice, VertexPositionColor.VertexElements);            
        }


        public void Create()
        {
            PrimitiveCount = points.Count() ;            

            VertexPositionColor[] vertexList = new VertexPositionColor[points.Count() + 1];
            int i = 0;
            foreach (var item in points)            
            {
                VertexPositionColor v;
                v.Position = item;
                v.Color = Color.White;
                vertexList[i++] =v;                
            }

            VertexPositionColor vclose;
            vclose.Position = points[0];
            vclose.Color = Color.White;
            vertexList[i] = vclose;                            

            VertexBuffer = new DynamicVertexBuffer(EngineStuff.GraphicsDevice, vertexList.Count() * VertexPositionColor.SizeInBytes, BufferUsage.WriteOnly);
            VertexBuffer.SetData(vertexList);

        }

        public void Subdivide()
        {
            List<Vector3> pnew = new List<Vector3>();

            for (int i = 0; i < points.Count(); i++)
            {
                pnew.Add(points[i]);
                Vector3 interpolatedPoint = -1f / 16f * getPoint(i - 1) + 9f / 16f * getPoint(i) + 9f / 16f * getPoint(i + 1) - 1f / 16f * getPoint(i + 2);
                //Vector3 interpolatedPoint = + 1f / 2f * getPoint(i) + 1f / 2f * getPoint(i + 1) ;
                Vector3  v = getPoint(i + 1)  ;
                pnew.Add(interpolatedPoint);
                

            }

            points = pnew.ToArray();
            Create();
        
        }

        Vector3 getPoint(int index)
        {
            if (index < 0)
            {
                int realindex = points.Count() + index ;
                return points[realindex];
            }
            else 
            {
                return points[index % (points.Count() ) ];
            }
        }

    }
}
